import { createStore, createLogger } from "vuex";
import api from '@/api/index';
// 获取node环境变量（development开发环境/production生产环境）
const env = process.env.NODE_ENV;
export default createStore({
    state: {
        // 登录状态
        isLogin: null,
        // 用户信息
        info: null,
        // 收藏列表
        storeList: null
    },
    mutations: {
        // 修改登录状态
        changeIsLogin(state, bool) {
            state.isLogin = bool;
        },
        // 修改用户信息
        changeInfo(state, payload) {
            state.info = payload;
        },
        // 修改收藏列表
        changeStoreList(state, payload) {
            state.storeList = payload;
        },
        // 删除收藏列表
        removeStoreList(state, id) {
            if (state.storeList === null) return;
            state.storeList = state.storeList.filter(item => {
                return +item.id !== +id;
            });
        }
    },
    actions: {
        // 登录
        async changeIsLoginAsync({ commit }) {
            let bool = false;
            let { code } = await api.checkLogin();
            if (+code === 0) bool = true;
            commit("changeIsLogin", bool)
        },
        // 获取用户信息
        async changeInfoAsync({ commit }) {
            let { code, data } = await api.userInfo();
            if (+code === 0) {
                commit("changeInfo", data);
            }
        },
        // 获取收藏列表信息
        async changeStoreListAsync({ commit }) {
            let { code, data } = await api.storeList();
            if (+code !== 0) data = [];
            commit('changeStoreList', data);
        }
    },
    // 生产环境不需要 createLogger 插件，开发环境下需要 createLogger 插件
    plugins: env === "production" ? [] : [createLogger()]
})